<template>
  <div class="book-room-page">
    <div class="banner">
      <h1>预约教室</h1>
      <p>为您的活动选择合适的教室和时间</p>
    </div>

    <div class="booking-container">
      <div class="calendar-section">
        <h3>选择日期</h3>
        <el-calendar v-model="selectedDate" :disabled-date="isDateDisabled" class="calendar" />
      </div>
      <div class="details-section">
        <h3>选择时间段</h3>
        <div class="time-slots">
          <el-button
            v-for="time in timeSlots"
            :key="time"
            :type="selectedTime.includes(time) ? 'primary' : 'default'"
            :disabled="!isTimeAvailable(time)"
            @click="toggleTimeSelection(time)"
          >
            {{ time }}
          </el-button>
        </div>
      </div>
    </div>

    <div class="additional-info">
      <h3>填写信息</h3>
      <el-input v-model="contactInfo" placeholder="请输入联系方式" />
      <el-input
        v-model="reason"
        type="textarea"
        placeholder="请输入预约原因"
        :rows="4"
      />
    </div>

    <div class="footer">
      <el-button type="primary" @click="handleSubmit">确认预约</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Api } from '@/api'
import { useUserStore } from '@/stores/user.js'

const userStore = useUserStore()

const selectedDate = ref(null)
const selectedTime = ref([])
const timeSlots = ref([
  '08:00-09:00', '09:00-10:00', '10:00-11:00', '11:00-12:00',
  '14:00-15:00', '15:00-16:00', '16:00-17:00', '17:00-18:00'
])
const contactInfo = ref('')
const reason = ref('')

// 获取预约列表
const appointments = ref([])
const fetchAppointments = async () => {
  try {
    const response = await Api.getAllAppointments()
    if (response.data.status === 200) {
      appointments.value = response.data.data.appointments
    }
  } catch (error) {
    console.error('获取预约列表失败:', error)
  }
}

onMounted(() => {
  fetchAppointments()
})

const isDateDisabled = (date) => {
  // 移除日期限制，允许选择任何日期
  return false
}

watch(selectedDate, (val) => {
  if (val) {
    selectedTime.value = []
  }
})

const isTimeAvailable = (time) => {
  // 移除时间段限制，允许选择任何时间段
  return true
}

const toggleTimeSelection = (time) => {
  const index = selectedTime.value.indexOf(time)
  if (index === -1) {
    selectedTime.value.push(time)
  } else {
    selectedTime.value.splice(index, 1)
  }
}

const handleSubmit = async () => {
  if (!selectedDate.value || selectedTime.value.length === 0 || !contactInfo.value || !reason.value) {
    ElMessage.error('请填写完整信息')
    return
  }

  try {
    const appointmentDateStr = new Date(selectedDate.value).toISOString().split('T')[0]

    // 为每个选中的时间段创建预约
    const promises = selectedTime.value.map(time => {
      const startTime = time.split('-')[0]
      const appointmentDateTime = `${appointmentDateStr}T${startTime}:00`

      const payload = {
        user_id: userStore.user.id,
        reason: reason.value,
        room_number: 1,
        appointment_date: appointmentDateTime,
        duration: 60,
        appointments_phone: contactInfo.value
      }

      return Api.bookConsultationRoom(payload)
    })

    const results = await Promise.all(promises)
    const allSuccess = results.every(res => res.data.status === 201)

    if (allSuccess) {
      ElMessage.success('预约成功！')
      // 清空选择
      selectedDate.value = null
      selectedTime.value = []
      contactInfo.value = ''
      reason.value = ''
      // 刷新预约列表
      fetchAppointments()
    } else {
      ElMessage.error('部分时间段预约失败，请重试')
    }
  } catch (error) {
    console.error('预约失败:', error)
    ElMessage.error('预约失败，请稍后再试')
  }
}
</script>

<style scoped>
.book-room-page {
  padding: 20px;
}

.banner {
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('/articles-banner.jpg');
  background-size: cover;
  background-position: center;
  color: white;
  text-align: center;
  padding: 4rem 1rem;
  margin-bottom: 2rem;
}

h1 {
  text-align: center;
  font-size: 2rem;
  margin-bottom: 10px;
}

p {
  text-align: center;
  color: #e3dfdf;
  margin-bottom: 20px;
}

.booking-container {
  display: flex;
  gap: 20px;
  align-items: flex-start;
  margin-bottom: 2rem;
}

.calendar-section {
  flex: 2;
  margin-right: 30px;
}

.details-section {
  flex: 1;
}

.time-slots {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 10px;
  margin-top: 10px;
}

.time-slots .el-button {
  width: 100%;
}

.additional-info {
  margin-top: 20px;
  margin-bottom: 2rem;
}

.additional-info h3 {
  margin-bottom: 10px;
}

.footer {
  text-align: center;
}

.el-button {
  margin: 5px 0;
}
</style>
